import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { toDoTypeEnum } from '~/store/oam/typings'
import type { MyToDoDataItemType, MyToDoPropsType } from './typings'
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import {
  ElSpace,
  ElLink,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker
} from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'
// import styles from '../index.module.scss'

export default defineComponent({
  name: 'MyToDoList',
  props: ['selectedKey', 'selectedValue', 'handleChangeOptionsVisible'],
  setup(props: MyToDoPropsType, { expose }) {
    const store = useStore()
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const formValues = reactive<MyToDoDataItemType>({})
    const toDoState = useVuexGetters('toDo', ['toDoTypeSelectList'])
    // 根据传入的key过滤dispatchType
    const handleFilterDispatchTypeByKey = (key: string) =>
      ({
        agency: 'toDo/GetTodoList',
        done: 'toDo/GetDoneList',
        cc: 'toDo/GetToCcList',
        submit: 'toDo/GetToSubmitList'
      }[key])
    // 切换父级组建radiolist的回调函数
    const handleChangeSelectedKeySearchList = () => {
      proSaasTableRef?.value?.searchFormRef?.resetFields()
      proSaasTableRef?.value?.toSearch()
    }

    onMounted(() => {
      store.dispatch('toDo/GetToDoTypeSelectList')
    })

    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
    }

    // 清空/下拉框值变 搜索
    const clearSearchTable = () => {
      if (formValues.taskTitle === '') {
        delete formValues.taskTitle // 标题
      }
      if (formValues.flowType === '') {
        delete formValues.flowType // 类型
      }
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 100)
    }

    const filterColumns = (selectedKey: string): TableColumnProps<MyToDoDataItemType>[] => [
      {
        label: '类型',
        prop: 'flowType',
        minWidth: 128,
        fixed: 'left',
        unFixed: true
      },
      {
        label: '标题',
        prop: 'taskTitle',
        minWidth: 120,
        showOverflowTooltip: true
      },
      {
        label: '发起人',
        prop: 'submitUserName',
        minWidth: 120
      },
      {
        label: '发起时间',
        prop: 'taskCreateTime',
        minWidth: 220,
        showOverflowTooltip: true
      },
      ...([
        // 不是提交时多添加
        selectedKey !== 'submit' && {
          label: '处理内容',
          prop: 'taskName',
          minWidth: 140
        },
        // 待办多添加
        selectedKey === 'agency' && {
          label: '时间',
          prop: 'remainingTime',
          minWidth: 220,
          showOverflowTooltip: true
        },
        // 已办多添加
        selectedKey === 'done' && {
          label: '处理时间',
          prop: 'taskCompleteTime',
          minWidth: 220,
          showOverflowTooltip: true
        },
        // 提交多添加
        selectedKey === 'submit' && {
          label: '状态',
          prop: 'flowStatusName',
          minWidth: 120,
          showOverflowTooltip: true
        }
      ].filter(Boolean) as TableColumnProps<MyToDoDataItemType>[]),
      {
        label: '操作',
        prop: 'options',
        align: 'center',
        fixed: 'right',
        unFixed: true,
        minWidth: 160,
        render: ({ row }) => (
          <ElSpace>
            <ElLink type="primary" onClick={() => props.handleChangeOptionsVisible(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 查看
            </ElLink>
          </ElSpace>
        )
      }
    ]
    expose({
      toSearch: handleChangeSelectedKeySearchList,
      searchFormRef: computed(() => proSaasTableRef?.value?.searchFormRef)
    })

    return () => {
      // 日期变时 搜索
      const datePickerChange = {
        onChange: () => {
          setTimeout(() => {
            proSaasTableRef.value!?.toSearch()
          }, 100)
        }
      }

      return (
        <>
          <ProSaasTable<MyToDoDataItemType>
            ref={proSaasTableRef}
            columns={filterColumns(props.selectedKey)}
            // hasIndex
            dispatchType={handleFilterDispatchTypeByKey(props.selectedKey)}
            searchParams={{
              time: undefined,
              beginTime: formValues.time?.[0]
                ? dayjs(formValues.time?.[0]).startOf('day').valueOf()
                : undefined,
              endTime: formValues.time?.[1]
                ? dayjs(formValues.time?.[1]).endOf('day').valueOf()
                : undefined
            }}
            searchFormProps={{
              model: formValues
            }}
            searchformResponsiveCol={[
              <ElFormItem key="taskTitle" prop="taskTitle">
                <ElInput
                  v-model={formValues.taskTitle}
                  placeholder="标题"
                  clearable
                  onKeydown={handleKeyDownEnterSubmitForm}
                  onClear={clearSearchTable}
                />
              </ElFormItem>,
              <ElFormItem key="flowType" prop="flowType">
                <ElSelect
                  v-model={formValues.flowType}
                  placeholder="类型"
                  clearable
                  onChange={clearSearchTable}
                >
                  {toDoState.toDoTypeSelectList?.value?.map((item: toDoTypeEnum) => (
                    <ElOption
                      key={item?.dictKey}
                      label={item?.dictValue}
                      value={item?.dictValue!}
                    />
                  ))}
                </ElSelect>
              </ElFormItem>,
              <ElFormItem key="time" prop="time">
                <ElDatePicker
                  v-model={formValues.time}
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  type="daterange"
                  clearable
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  {...datePickerChange}
                />
              </ElFormItem>
            ]}
          />
        </>
      )
    }
  }
})
